package com.bdweb.mokuai;

import  com.bdweb. mokuai.logWrite;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;

public class TCPClient {

    Socket  s;
    OutputStream outputStream=null;
    public  TCPClient(String ip,int port,String message) throws IOException, InterruptedException {
        byte[] bytes = hexStrToBinaryStr(message);
     new Thread(new Runnable() {
             @Override
          public void run() {
                 //1.创建Socket对象


                 // s.setKeepAlive(true);
                 //设置最大连接超时时间，超过此时间，无响应则断开连接

                 try {
                     s = new Socket(ip, port);

                 } catch (IOException e) {
                     try {
                         new logWrite(ip+"连接失败");
                     } catch (IOException ex) {
                         throw new RuntimeException(ex);
                     }
                 }

                 // boolean isAvailable = isTCPConnectionAvailable(ip, port);
                 /* if (isAvailable){*/
                 boolean flag =false;
                 try {
                     flag = s.getKeepAlive();
                 } catch (SocketException e) {
                     throw new RuntimeException(e);
                 }
                 if (!flag) {
                     boolean connected = s.isConnected();
                     if (connected) {
                         //2.可以从连接通道中获取输出流
                         System.out.println("连接成功");
                         try {
                             new logWrite(s.getInetAddress()+"连接成功");
                         } catch (IOException e) {

                             throw new RuntimeException(e);
                         }
                         try {
                             outputStream = s.getOutputStream();
                         } catch (IOException e) {

                            e.printStackTrace();

                         }
                         //3.发送数据

                         try {
                             outputStream.write(bytes);
                             outputStream.flush();
                         } catch (IOException e) {

                             throw new RuntimeException(e);



                         }

                     }

                 } else {

                     System.out.println("TCP断开连接");

                 }

             }
   }).start();


 }
/*    public static boolean isTCPConnectionAvailable(String ipAddress, int port) {
        try (Socket socket = new Socket()) {
           // socket.sendUrgentData(0xFF); // 发送心跳包
            InetSocketAddress address = new InetSocketAddress(ipAddress, port);
            socket.connect(address, 1000); // 设置超时时间为1秒
            return true;
        } catch (IOException e) {
            System.out.println(e+"连接断开");
            return false;
        }
    }*/
    /**
     * 将十六进制的字符串转换成字节数组
     *
     * @param hexString
     * @return
     */
    public static byte[] hexStrToBinaryStr(String hexString) {

        if (hexString.length()==0) {
            return null;
        }

        hexString = hexString.replaceAll(" ", "");

        int len = hexString.length();
        int index = 0;

        byte[] bytes = new byte[len / 2];

        while (index < len) {

            String sub = hexString.substring(index, index + 2);

            bytes[index/2] = (byte)Integer.parseInt(sub,16);

            index += 2;
        }


        return bytes;
    }

    /**
     * 将字节数组转换成十六进制的字符串
     *
     * @return
     */
    public static String BinaryToHexString(byte[] bytes) {
        String hexStr = "0123456789ABCDEF";
        String result = "";
        String hex = "";
        for (byte b : bytes) {
            hex = String.valueOf(hexStr.charAt((b & 0xF0) >> 4));
            hex += String.valueOf(hexStr.charAt(b & 0x0F));
            result += hex + " ";
        }
        return result;
    }



}
